package com.wiscamp.ninechapters.problems.application.handlers;

import com.wiscamp.ninechapters.problems.domain.events.AssignmentCreatedEvent;
import com.wiscamp.ninechapters.problems.domain.services.AssignmentService;
import com.wiscamp.ninechapters.problems.domain.services.TaskService;
import cube.ddd.aspect.HandleServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AssignmentCreatedEventHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final AssignmentService assignmentService;

    private final TaskService taskService;

    @Autowired
    public AssignmentCreatedEventHandler(AssignmentService assignmentService, TaskService taskService) {
        this.assignmentService = assignmentService;
        this.taskService = taskService;
    }

    @Async
    @HandleServiceException
    @EventListener(AssignmentCreatedEvent.class)
    public void handleEvent(AssignmentCreatedEvent event) {
        long assignmentId = event.getAssignmentId();
        logger.warn("handling assignment created event: {}", assignmentId);
        var assignment = assignmentService.getAssignment(assignmentId);
        taskService.createTaskByAssignment(assignment);
        logger.warn("handled assignment created event.");
    }
}
